//
//  SIEmoticon.swift
//  SinaImiate
//
//  Created by xiaoming on 16/7/10.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit


class SIEmoticon: NSObject {
    
    /// 表情类型,true 对应emoji   false 对应 图片
    var type = false
    /// 表情字符串
    var chs: String?
    
    /// 表情图片名称, 用于本地图文混排
    var png: String?
    
    /// emoji的十六进制编码
    var code: String? {
        didSet {
            
            guard let code = code else {
                return
            }
            
            let scanner = Scanner(string: code)
            
            var result: UInt32 = 0
            scanner.scanHexInt32(&result)
            
            emoji = String(Character(UnicodeScalar(result)))
        }
    }
    
    /// 表情使用次数
    var times: Int = 0
    
    /// emoji的字符串
    var emoji: String?
    
    /// 图片表情对应bundle里的模型
    var directory: String?
    
    /// 图片表情对应的图像
    var image: UIImage? {
        
        if type {
            
            return nil
        }
        
        guard let directory = directory,
            png = png,
            path = Bundle.main.pathForResource("HMEmoticon.bundle", ofType: nil),
            bundle = Bundle(path: path)
            else {
                return nil
        }
        
        return UIImage(named: "\(directory)/\(png)", in: bundle, compatibleWith: nil)
        
    }
    
    /// 将当前的图像生成对应的属性文本
    ///
    func imageText(font: UIFont) -> AttributedString {
        
        guard let image = image else {
            
            return AttributedString(string: "")
            
        }
        
        let attachment = SIEmoticonAttachment()
        
        attachment.chs = chs
        attachment.image = image
        
        let height = font.lineHeight
        
        attachment.bounds = CGRect(x: 0, y: -4, width: height, height: height)
        
        let attrStrM = NSMutableAttributedString(attributedString: AttributedString(attachment: attachment))
        attrStrM.addAttributes([NSFontAttributeName: font], range: NSRange(location: 0, length: 1))
        
        return attrStrM
        
    }
    
    override var description: String {
        
        return yy_modelDescription()
    }

}
